package com.cmonbaby.adapter;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

/**
 * SwipeRefresh事件监听
 */
public class SwipeListener {

    private SwipeRefreshLayout swipeRefresh;
    private SwipeRefreshHelper swipeRefreshHelper; // 下拉刷新的工具类
    private OnSwipeListener swipeListener;

    private SwipeListener(Builder builder) {
        this.swipeRefresh = builder.swipeRefresh;
        this.swipeListener = builder.swipeListener;
        int[] colorRes = builder.colorRes; // 下拉颜色
        if (swipeRefresh != null) {
            if (colorRes == null) {
                swipeRefreshHelper = SwipeRefreshHelper.createSwipeRefreshHelper(swipeRefresh);
            } else {
                swipeRefreshHelper = SwipeRefreshHelper.createSwipeRefreshHelper(swipeRefresh, colorRes);
            }
        }
        init();
    }

    private void init() {
        // 下拉刷新的操作 */
        if (swipeRefreshHelper != null) {
            swipeRefreshHelper.setOnSwipeRefreshHelperListener(() -> { // 下拉刷新，等同于重新加载
                dismissSwipeRefresh();
                if (swipeListener != null) swipeListener.onRefresh();
            });
        }
    }

    /** 显示SwipeRefresh */
    public void showSwipeRefresh() {
        if (swipeRefresh != null && !swipeRefresh.isRefreshing()) {
            swipeRefresh.setRefreshing(true);
        }
    }

    /** 隐藏SwipeRefresh */
    public void dismissSwipeRefresh() {
        if (swipeRefresh != null && swipeRefresh.isRefreshing()) {
            swipeRefresh.setRefreshing(false);
        }
    }

    /** 下拉刷新接口 */
    public interface OnSwipeListener {

        void onRefresh();
    }

    static final class Builder {

        private SwipeRefreshLayout swipeRefresh;
        private OnSwipeListener swipeListener;
        private int[] colorRes; // 下拉颜色

        Builder() {
        }

        Builder swipeRefresh(SwipeRefreshLayout swipeRefresh) {
            this.swipeRefresh = swipeRefresh;
            return this;
        }

        Builder swipeListener(OnSwipeListener swipeListener) {
            this.swipeListener = swipeListener;
            return this;
        }

        Builder colorRes(int... colorRes) {
            this.colorRes = colorRes;
            return this;
        }

        SwipeListener build() {
            return new SwipeListener(this);
        }
    }
}
